<?php
/**
 * 从gb网站获取品类数据
 * 2018-5-21
 * liugang
 */
namespace app\controllers\crontab;

use yii;
use app\models\marketing\MailGroup;
use app\components\Site;

use app\models\Elog;
use GuzzleHttp\Client;

class GetGbCategoryInfoController extends \app\base\Controller
{
    // 获取gb品类接口头配置信息
    private $getGbCategoryHeader = [
        'dev'   => [
            "domain" => "",
            "method" => "getCategoryListForLinkageSelect",
            "service" => "com.globalegrow.mgoods.spi.inter.ICategoryService",
            "version" => "1.0.0",
            "tokenId" => "487d842de4e1c9b9c99ac868c7af15a4",
            "url" => ""
        ],
        'test'   => [
            "domain" => "",
            "method" => "getCategoryListForLinkageSelect",
            "service" => "com.globalegrow.mgoods.spi.inter.ICategoryService",
            "version" => "1.0.0",
            "tokenId" => "487d842de4e1c9b9c99ac868c7af15a4",
            "url" => ""
        ],
        'product'   => [
            "domain" => "",
            "method" => "getCategoryListForLinkageSelect",
            "service" => "com.globalegrow.mgoods.spi.inter.ICategoryService",
            "version" => "1.0.0",
            "tokenId" => "5dd73f1f0412b1a8f483ed0655b259b4",
            "url" => ""
        ]
    ];
    // 获取gb品类接口地址
    private $gbCategoryApiUrl = [
        'dev'   => 'http://10.40.2.62:2087/gateway/',
        'test'   => 'http://10.40.2.62:2087/gateway/',
        'product'   => 'http://gb-obs-outer.gw-soa.com/gateway/'
    ];



    /*
     * 定时获取并保存gb站点品类数据
     * /crontab/get-gb-category-info/get-gb-category-data?site=marketing_email 每天执行一次
     * @user liugang
     * @date 2018-5-21
     */
    public function actionGetGbCategoryData()
    {
        ignore_user_abort(true); 
        set_time_limit(0);
        
        
        $client = new Client(['timeout' => 60]);
        
        $postData = [];
        $postData['header'] = $this->getGbCategoryHeader[YII_ENV];
        $postData['body'] = [
            'siteCode'          => 'GB'             // 站点编码
        ];
        $response = $client->request('POST', $this->gbCategoryApiUrl[YII_ENV], ['json' => $postData]);
        
         try{ 
            $responseJsonString = $response->getBody()->getContents();
            $returnData = \GuzzleHttp\json_decode($responseJsonString,true);
            if ($returnData['body']) {
               $returnBody  = \GuzzleHttp\json_decode($returnData['body'],true);
            }
//            var_dump($returnBody);exit;
            if($returnBody['code'] == 0) {
                
                // 处理数据
                if($returnBody['data']) {
                    
                    // 初始化表结构
                    Yii::$app->db->createCommand("DROP TABLE IF EXISTS gearbest_category_data")->execute();
                    Yii::$app->db->createCommand("CREATE TABLE `gearbest_category_data` (
                                                `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
                                                `category_grade` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '品类级别',
                                                `category_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '品类id',
                                                `category_name` varchar(64) NOT NULL DEFAULT '' COMMENT '品类名称',
                                                `parent_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父级品类id',
                                                `min_category_relation` varchar(255) NOT NULL DEFAULT '' COMMENT '最小品类id与所有父级品类id的关系，以，分割',
                                                `is_leaves` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否为最小分类',
                                                PRIMARY KEY (`id`),
                                                KEY `category_grade` (`category_grade`) USING BTREE,
                                                KEY `parent_id` (`parent_id`) USING BTREE,
                                                KEY `min_category_relation` (`min_category_relation`) USING BTREE,
                                                KEY `is_leaves` (`is_leaves`) USING BTREE
                                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='GB站品类数据表';")->execute();
                    
                    $insertArr = [];
                    
                    $insertSql = "insert into gearbest_category_data(category_grade,category_id,category_name,parent_id,min_category_relation,is_leaves) values";
                    
                    foreach($returnBody['data'] as $data) {
                        $category_grade = 1;
                        $categoryRelation = ','.$data['id'].',';
                        if($data['isLeaves'] == 1) {
                            $insertArr[] = "($category_grade,{$data['id']},\"".$data['categoryName']."\",{$data['parentId']},'{$categoryRelation}',{$data['isLeaves']})";
                        } else {
                            $insertArr[] = "($category_grade,{$data['id']},\"".$data['categoryName']."\",{$data['parentId']},'',{$data['isLeaves']})";
                            $this->getMinCategory($category_grade, $categoryRelation, $insertArr, $data['subCategoryList']);
                        }
                        
                    }
                    
                    if($insertArr) {
                        $insertSql .= join(',',$insertArr);
//                        var_dump($insertSql);exit;
                        // 数据写入edm数据表
                        Yii::$app->db->createCommand($insertSql)->execute();
                    }
                    
                    
                    
                }
                
//                Elog::logCrontab($curPage.'-'.$totalOrderNums, 'actionNewGetGbOrderGoodsData','info');
                
                echo '数据同步完成！';
                
                
            } else {
                echo '请求数据失败！';
            }
            
           
        } catch(\Exception $exp) {
            echo $exp->getTraceAsString();
        }
        
        
    }
    
    public function getMinCategory($category_grade, $categoryRelation, &$return = [], $datas = [])
    {
        $category_grade++;
        foreach($datas as $data) {
            $categoryRelation1 = $categoryRelation ? $categoryRelation.$data['id'].',' : ','.$data['id'].',';
            if($data['isLeaves'] == 1) {
                $return[] = "($category_grade,{$data['id']},\"".$data['categoryName']."\",{$data['parentId']},'{$categoryRelation1}',{$data['isLeaves']})";
            } else {
                $return[] = "($category_grade,{$data['id']},\"".$data['categoryName']."\",{$data['parentId']},'',{$data['isLeaves']})";
                $this->getMinCategory($category_grade, $categoryRelation1, $return, $data['subCategoryList']);
            }
        }
        return '';
    }
    
    
}